package net.siufung.core.template.freemarker;

import cn.hutool.core.util.ArrayUtil;
import com.google.common.base.Strings;
import freemarker.cache.URLTemplateLoader;
import lombok.Setter;
import net.siufung.core.utils.StringPool;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

/**
 * 远程URL地址的方式实现模板加载
 * @author 陈建峰
 * @since 2022/8/31 4:06 下午
 */
public class RemoteTemplateLoader extends URLTemplateLoader {

    /**
     * 远程模板文件的存储路径（目录)
     */
    @Setter
    private String remotePath;

    /**
     * 包含路径
     */
    private String[] includePaths;


    public RemoteTemplateLoader(String remotePath) {
        if (Strings.isNullOrEmpty(remotePath)) {
            throw new IllegalArgumentException("remotePath is null");
        }
        this.remotePath = canonicalizePrefix(remotePath);
        if (this.remotePath.indexOf(StringPool.SLASH) == 0) {
            this.remotePath =
                    this.remotePath.substring(this.remotePath.indexOf(StringPool.SLASH) + 1);
        }
    }

    @Override
    public Object findTemplateSource(String name) throws IOException {
        if(ArrayUtil.isNotEmpty(this.includePaths) && Arrays.asList(this.includePaths).contains(name)){
            return super.findTemplateSource(name);
        }
        return null;
    }

    @Override
    protected URL getURL(String name) {
        String fullPath = this.remotePath + name;
        fullPath = fullPath.replace("_zh", "").replace("_CN","");
        if (( StringPool.SLASH.equals(this.remotePath)) && (!isSchemeLess(fullPath))) {
            return null;
        }
        URL url = null;
        try {
            url = new URL(fullPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return url;
    }

    private static boolean isSchemeLess(String fullPath) {
        int i = 0;
        int ln = fullPath.length();

        if ((i < ln) && (fullPath.charAt(i) == StringPool.C_SLASH)){
            i++;
        }
        while (i < ln) {
            char c = fullPath.charAt(i);
            if (c == StringPool.C_SLASH){
                return true;
            }
            if (c == StringPool.C_COLON){
                return false;
            }
            i++;
        }
        return true;
    }

    public void setPaths(String paths) {
        if (!Strings.isNullOrEmpty(paths)) {
            this.includePaths = paths.split(StringPool.SEMICOLON);
        }
    }
}
